<!-- 参数配置 -->
<template>
	<div>
		<!-- 搜索表单 -->
		<yd-form ref="myForm" :options="formOptions" :model="queryParams" @change="handlerSelectChange">
			<template #form-btn>
				<div>
					<el-button class="yd-form-btn" type="primary" @click="getList">查询</el-button>
				</div>
			</template>
		</yd-form>
		<!--查询列表-->
		<YdTable
			ref="multipleTable"
			:formData="queryParams"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			@sizeChangeHandler="getList"
			@currentChangeHandler="getList"
			@sortChangeHandler="getList"
			@selectionChangeHandler="handleSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog v-model="open" :title="title" width="500px" append-to-body center>
			<el-form ref="conForm" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="参数名称" prop="publicName">
					<el-input v-model="form.publicName" placeholder="请输入参数名称" />
				</el-form-item>
				<el-form-item label="参数键名" prop="publicKey">
					<el-input v-model="form.publicKey" :disabled="disabled" placeholder="请输入参数键名" />
				</el-form-item>
				<el-form-item label="参数键值" prop="publicValue">
					<el-input v-model="form.publicValue" placeholder="请输入参数键值" />
				</el-form-item>
				<el-form-item label="系统内置" prop="systemFlag">
					<el-radio-group v-model="form.systemFlag">
						<el-radio v-for="dict in typeOptions" :key="dict.value" :label="dict.value">{{ dict.label }} </el-radio>
					</el-radio-group>
				</el-form-item>
				<!-- <el-form-item label="备注" prop="remarks">
					<el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
				</el-form-item> -->
			</el-form>
			<template #footer>
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="Parameters" lang="ts">
import { listConfig, getConfig, delConfig, addConfig, updateConfig, exportConfig, clearCache } from '@/api/admin/operationConfig/parameters';
import { getCurrentInstance, reactive, ref, toRefs } from 'vue';

const { proxy }: any = getCurrentInstance();

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 选中数组的名称
const configNames = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
const isInit = ref(false);
// 弹出层标题
const title = ref('');
//控制是否可输入
const disabled = ref(false);
// 是否显示弹出层
const open = ref(false);
// 类型数据字典
const typeOptions = ref([
	{ label: '是', value: '1' },
	{ label: '否', value: '0' },
]);
const formOptions = reactive<FormOptionType>([
	{
		type: 'select',
		prop: 'systemFlag',
		label: '系统内置',
		attrs: {
			clearable: true,
		},
		placeholder: '请选择系统内置',
		children: [
			{ label: '全部', value: '' },
			{ label: '是', value: '1' },
			{ label: '否', value: '0' },
		],
	},
	{
		type: 'input',
		prop: 'publicName',
		label: '参数名称',
		attrs: {
			clearable: true,
		},
		placeholder: '请输入参数名称',
	},
	{
		type: 'input',
		prop: 'publicKey',
		label: '参数键名',
		attrs: {
			clearable: true,
		},
		placeholder: '请输入参数键名',
	},
	{
		type: 'date-picker',
		label: '时间范围',
		prop: 'dateRange',
		dateType: 'datetimerange',
		enableCrossDay: true,
		span: 10,
		// shortcutsKeys: ['last1h', 'today', 'lastDay'],
		// defaulShortcutsKey: 'lastlh',
		defaulShortcutsKey: 'today',
		attrs: {
			clearable: true,
		},
	},
]);
// 查询参数
let queryParams = reactive<any>({
	pageNum: 1,
	pageSize: 10,
	dateRange: [],
});
// 列表配置
let tableConfig = reactive<any>({
	// url: listConfig,
	columns: [
		{
			label: '参数名称',
			prop: 'publicName',
			showOverFlowToolTip: true,
		},
		{
			label: '参数键名',
			prop: 'publicKey',
			showOverFlowToolTip: true,
		},
		{
			label: '参数键值',
			prop: 'publicValue',
		},
		{
			label: '系统内置',
			prop: 'systemFlag',
			width: 100,
			formatter(row: any, val: any) {
				return typeOptions.value.filter((item: any) => item.value === val)[0].label;
			},
		},
		// {
		// 	label: '备注',
		// 	prop: 'remarks',
		// },
		{
			label: '更新时间',
			prop: 'updateTime',
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '修改',
					handler: (scope: any) => handleUpdate(scope.row),
					permi: ['system:config:edit'],
				},
				{
					text: '删除',
					handler: (scope: any) => handleDelete(scope.row),
					permi: ['system:config:remove'],
				},
			],
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['system:config:add'], handler: () => handleAdd() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['system:config:edit'], disable: 'single', handler: () => handleUpdate() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['system:config:remove'], disable: 'multiple', handler: () => handleDelete() },
		{
			name: '清理缓存',
			icon: 'yd-icon-refresh',
			permi: ['system:config:cleanCache'],
			disable: 'multiple',
			handler: () => handleClearCache(),
		},
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: false,
});
// 列表数据
let tableData = reactive({
	data: [],
	total: 0,
});
// 表单参数
const data = reactive({
	form: { systemFlag: 1 },
});
const { form }: any = toRefs(data);
// 表单校验
const rules = ref({
	publicName: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
	publicKey: [{ required: true, message: '参数键名不能为空', trigger: 'blur' }],
	publicValue: [{ required: true, message: '参数键值不能为空', trigger: 'blur' }],
});

function handlerSelectChange(options: BaseOptionType, value: any) {
	if (options.type === 'select') {
		queryParams.systemFlag = value;
	}
	if (options.type === 'date-picker') {
		queryParams.startTime = value[0];
		queryParams.endTime = value[1];
	}
}

/** 查询参数列表 */
function getList() {
	tableConfig.loading = true;
	queryParams.current = queryParams.pageNum;
	queryParams.size = queryParams.pageSize;
	listConfig(queryParams)
		.then((response: any) => {
			tableData.data = response.data.records;
			tableConfig.pagination.total = response.data.total;
			tableConfig.loading = false;
		})
		.catch((e: any) => {
			tableConfig.loading = false;
		});
}
// 取消按钮
function cancel() {
	open.value = false;
	reset();
}
// 表单重置
function reset() {
	form.value = {
		publicId: undefined,
		publicName: undefined,
		publicKey: undefined,
		publicValue: undefined,
		systemFlag: '1',
	};
}
/** 搜索按钮操作 */
function handleQuery() {
	queryParams.pageNum = 1;
	getList();
}
/** 新增按钮操作 */
function handleAdd() {
	reset();
	open.value = true;
	disabled.value = false;
	title.value = '添加参数';
}
// 多选框选中数据
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.publicId);
	configNames.value = selection.map((item: any) => item.publicname);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}
/** 修改按钮操作 */
function handleUpdate(row?: any) {
	reset();
	const configId = row ? row.publicId : ids.value;
	getConfig(configId).then((response: ApiResponse) => {
		form.value = response.data;
		open.value = true;
		disabled.value = true;
		title.value = '修改参数';
	});
}
/** 提交按钮 */
function submitForm() {
	proxy.$refs['conForm'].validate((valid: boolean) => {
		if (valid) {
			if (form.value.publicId !== undefined) {
				updateConfig(form.value).then((response: ApiResponse) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('修改成功');
						open.value = false;
						getList();
					} else {
						proxy.$modal.msgError(response.msg);
					}
				});
			} else {
				addConfig(form.value).then((response) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('新增成功');
						open.value = false;
						getList();
					} else {
						proxy.$modal.msgError(response.msg);
					}
				});
			}
		}
	});
}
/** 删除按钮操作 */
function handleDelete(row?: any) {
	const configIds = row === undefined ? ids.value : row.publicId;
	const configName = row === undefined ? configNames.value : row.publicName;
	proxy.$modal
		.confirm('是否确认删除参数名称为"' + configName + '"的数据项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(function () {
			return delConfig(configIds);
		})
		.then((res: ApiResponse) => {
			// 删除后的总条数
			// let totalCount = row ? tableData.total - 1 : tableData.total - ids.value.length;
			// 计算删除后的总页数
			// let totalPage = Math.ceil(totalCount / queryParams.pageSize);
			// 如果删除后的总页数小于1, 置为1
			// totalPage = totalPage < 1 ? 1 : totalPage;
			// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
			// queryParams.pageNum = queryParams.pageNum > totalPage ? totalPage : queryParams.pageNum;
			if (res.code === 0) {
				getList();
				proxy.$modal.msgSuccess('删除成功');
			} else {
				proxy.$modal.msgError(res.msg);
			}
		})
		.catch(function () {});
}
/** 清理缓存按钮操作 */
function handleClearCache() {
	clearCache().then((response: ApiResponse) => {
		if (response.code === 0) {
			proxy.$modal.msgSuccess('清理成功');
		} else {
			proxy.$modal.msgError(response.msg);
		}
	});
}
getList();
</script>
